package com.ws.demo.second.server;

import com.alibaba.fastjson.JSONObject;
import com.ws.demo.second.vo.WsVo;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.DateUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint("/ws/{userId}")
public class WebSocketServer {

    /**
     * 统计当前在线数量
     */
    private static final AtomicInteger onlineCount = new AtomicInteger(0);

    public static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    private String userId;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        // 连接成功执行方法
        int currentOnlineCount = onlineCount.incrementAndGet();
        System.out.println(this);

        System.out.println("当前" + now() + "在线人数：" + currentOnlineCount + ", 当前用户id：" + userId);

        sessionMap.put(userId, session);

        this.userId = userId;

        // 发送消息给客户端，提示连接成功
        JSONObject msg = new JSONObject();
        msg.put("from", "服务端");
        msg.put("to", userId);
        msg.put("msg", "服务器连接成功");

        sendMsg(session, msg.toJSONString());

    }

    /**
     * 接收客户端发送的消息
     * @param message 消息内容
     * @param session session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        sendMsg(session, message);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
        System.out.println(throwable.toString());
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("移除对象：" + this.userId);
        sessionMap.remove(this.userId);
        onlineCount.decrementAndGet();
        System.out.println();
    }

    public void sendMsg(Session session, String message) {
        WsVo vo = JSONObject.parseObject(message, WsVo.class);

        Session targetSession = sessionMap.get(vo.getTo());
        if (targetSession == null) {
            System.out.println("目标用户已下线");
            return;
        }

        try {
            targetSession.getBasicRemote().sendText(now() + message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMsg(String userId, String message) {
        Session session = sessionMap.get(userId);
        if (session == null) {
            System.out.println("目标不存在");
            return;
        }
        sendMsg(session, message);
    }


    private String now() {
        return DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss", Locale.CHINESE);
    }

}
